/*
 * Copyright 2006-2007 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var clockStopped = true;
var clockTimer;

/**
 * Starts the game clock and changes the button text
 */
function startClock() {
    clockStopped = false;
    clearTimeout(clockTimer);
    clockTimer = setTimeout("runClock()", 1000);

    clockBtn = jq('#clock-btn');
    clockBtn.text("stop clock");
    clockBtn.unbind('click', startClock);
    clockBtn.bind('click', stopClock);
}

/**
 * Stops the game clock and changes the button text
 */
function stopClock() {
    clockStopped = true;
    clearTimeout(clockTimer);

    clockBtn = jq('#clock-btn');
    clockBtn.text("start clock");
    clockBtn.unbind('click', stopClock);
    clockBtn.bind('click', startClock);
}

/**
 * Ticks the clock by one and schedules for the next click
 */
function runClock() {
    if (!clockStopped) {
        clockTimer = setTimeout("runClock()", 1000);
    }
    else {
        clearTimeout(clockTimer);
        return;
    }

    var jqSeconds = jq("input[name='game.secondsRemaining']");
    var jqMinutes = jq("input[name='game.minutesRemaining']");

    var seconds = jqSeconds.val();
    if (seconds == 0) {
        var minutes = jqMinutes.val();
        if (minutes > 1) {
            minutes = minutes - 1;
            seconds = 59;
            jqSeconds.val(seconds);
            jqMinutes.val(minutes);

            // update display
            jq("#secondsRemaining").html(seconds);
            jq("#minutesRemaining").html(minutes);
        }
        else {
            jqSeconds.val(0);
            jqMinutes.val(0);

            // update display
            jq("#secondsRemaining").html(0);
            jq("#minutesRemaining").html(0);

            alert("End of Game!");

            stopClock();
            clockBtn = jq('#clock-btn');
            clockBtn.text("game over");
            clockBtn.attr('disabled', true);
        }
    }
    else {
        seconds = seconds - 1;
        jqSeconds.val(seconds);

        // update display
        jq("#secondsRemaining").html(seconds);
    }
}

/**
 * Increments the home or visiting team score
 *
 * @param teamIndicator - indicator for which team to update, 0 for home team, 1 for visiting
 * @param pointIncrement - number of points for each increment
 * @param fieldName - name of the field that was clicked
 */
function updateScore(teamIndicator, pointIncrement, fieldName) {
    var jqHomePoints = jq("input[name='game.homePoints']");
    var jqVisitingPoints = jq("input[name='game.visitingPoints']");

    // get the field change amount
    var jqField = jq("input[name='" + fieldName + "']");
    var previousCnt = 0;
    if (jqField.data('previousCnt')) {
        previousCnt = jqField.data('previousCnt');
    }
    jqField.data('previousCnt', jqField.val());

    var increment = parseInt(jqField.val()) - previousCnt;
    var points = increment * pointIncrement;

    if (teamIndicator) {
        var curPoints = parseInt(jqHomePoints.val());
        curPoints += points;
        jqHomePoints.val(curPoints);

        // update display
        jq("#homePoints").html(curPoints);
    }
    else {
        var curPoints = parseInt(jqVisitingPoints.val());
        curPoints += points;
        jqVisitingPoints.val(curPoints);

        // update display
        jq("#visitingPoints").html(curPoints);
    }
}

/**
 * Makes request to save the game play getting the description back which is then added to the game plays span
 *
 * @param playerNum - number for the player who made the play
 * @param property - name of the property for the field that was clicked
 */
function saveGamePlay(playerNum, property) {
    var queryData = {};

    queryData.methodToCall = 'saveGamePlay';
    queryData.skipViewInit = 'true';
    queryData.formKey = jq("input#formKey").val();
    queryData.newGamePlayNumber = playerNum;
    queryData.newGamePlayProperty = property;
    queryData.newGamePlayMinutes = jq("input[name='game.minutesRemaining']").val();
    queryData.newGamePlaySeconds = jq("input[name='game.secondsRemaining']").val();
    queryData.newGamePlayHalf = jq("input[name='game.half']").val();

    jq.ajax({
        url: jq("form#kualiForm").attr("action"),
        dataType: "json",
        data: queryData,
        beforeSend: null,
        complete: null,
        success: function (data) {
            var playDesc = data.playDesc;

            // add message to game plays
            var gamePlaySpan = jq("#game-plys_span");
            if (gamePlaySpan.length > 0) {
                gamePlaySpan.append("<br/>" + playDesc);
            }
        }
    });
}

/**
 * Creates the spinner widget for an input
 *
 * @param id - id for the control to apply the spinner to
 * @param options - options for the spinner
 */
function createSpinner(id, options) {
    jq("#" + id).spinit(options);
}

/**
 * Highlights a field by changing the color to red
 *
 * @param id - id for the control to highlight
 */
function highlightHigh(id) {
    jq("#" + id).css('color', 'red');
}

